package com.itheima.dubbo.mysql.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.commons.model.domain.UserLoginDate;
import com.itheima.commons.model.vo.ReturnDataVo;
import com.itheima.dubbo.interfaces.UserLoginDateApi;
import com.itheima.dubbo.mysql.mapper.UserLoginDateMapper;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/*
 * @ProjectName:project-exercise
 * @Package:com.itheima.dubbo.mysql.impl
 * @ClassName:UserLoginDateApiImpl
 * @Author:ZHANG
 * @Date:2021-12-19 15:27
 * @Description:
 */
@Service
public class UserLoginDateApiImpl implements UserLoginDateApi {

    @Autowired
    private UserLoginDateMapper userLoginDateMapper;


    @Override
    public Long queryOneDayLoginUser(Date date) {
        String dateStr = DateUtil.formatDate(date);
        //查询某天的登录次数，模糊查询；不需要去重，
        Integer selectCount = userLoginDateMapper.selectCount(Wrappers.lambdaQuery(UserLoginDate.class)
                .like(UserLoginDate::getLoginDate, dateStr + "%"));
        return Convert.toLong(selectCount);
    }

    @Override
    public Long queryActiveUserByPastPeriod(String days, Date date) {
        //遍历次数
        Integer dayCount = Convert.toInt(days);
        Integer selectCount = 0;
        Integer index = -1;
        for (Integer count = dayCount; count > 0; count--) {
            String dateStr = DateUtil.formatDate(DateUtil.offsetDay(date, index));
            //求每一天的活跃人数
            QueryWrapper<UserLoginDate> wrapper = new QueryWrapper<>();
            wrapper.select("DISTINCT user_id").like("login_date", dateStr + "%");
            //累加每一天
            selectCount += userLoginDateMapper.selectCount(wrapper);
            index--;
        }
        return Convert.toLong(selectCount);
    }
}
